class CulturalHeritage::CulturalHeritagePropertiesController < ApplicationController
  #INMUEBLES
  # before_filter :authenticate_user!
  # GET /cultural_heritage/cultural_heritages
  # GET /cultural_heritage/cultural_heritages.xml
  include ApplicationHelper
  def index
    @title_view = 'Patrimonio Cultural Inmueble'
    @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:group=>[2],:deleted=>[0]})
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @cultural_heritage_cultural_heritages }
        format.json  { render :json => @cultural_heritage_cultural_heritages }
    end
  end

  # GET /cultural_heritage/cultural_heritages/1
  # GET /cultural_heritage/cultural_heritages/1.xml
  def show
    @title_view = 'Patrimonio Cultural Inmueble'
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
    if @cultural_heritage_cultural_heritage.father_maximum_id != -1
      @father_node   = CulturalHeritage::CulturalHeritage.find(@cultural_heritage_cultural_heritage.father_maximum_id)      
    else
      #aca funciona
      @father_node = @cultural_heritage_cultural_heritage     
    end
    @cultural_heritage_cultural_heritage_models = @cultural_heritage_cultural_heritage.list_models
    @cultural_heritage_cultural_heritage_videos = @cultural_heritage_cultural_heritage.list_videos
    @cultural_heritage_cultural_heritage_avatars = @cultural_heritage_cultural_heritage.list_avatars
    @cultural_heritage_cultural_heritage_researches = @cultural_heritage_cultural_heritage.list_researches
    @json = @cultural_heritage_cultural_heritage.to_gmaps4rails do |cultural_heritage, marker|
      marker.infowindow  cultural_heritage.define_info_window_for_marker_for_maps(root_url)
      marker.title   cultural_heritage.name
      marker.sidebar "Ubicacion"
    end
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @cultural_heritage_cultural_heritage }
        format.json  { render :json => @cultural_heritage_cultural_heritage }
    end
  end

  # GET /cultural_heritage/cultural_heritages/new
  # GET /cultural_heritage/cultural_heritages/new.xml
  def new
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @title_view = 'Patrimonio Cultural Inmueble'
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.new()
      @cultural_heritage_cultural_heritage.group=2
      @states = CulturalHeritage::State.find(:all,:conditions=>{:deleted=>[0]})
      @groups = CulturalHeritage::Group.find(:all,:conditions=>{:deleted=>[0]})
      @subgroups = CulturalHeritage::SubGroup.find(:all,:conditions=>{:deleted=>[0]})
      @typologies = []
      @inmuebles = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
      @culturalinstitutions = []
      @culturalinstitutionstypes = CulturalHeritage::TypeCulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
      @periods = []
      @cultures = []
      @styles = CulturalHeritage::Style.find(:all,:conditions=>{:deleted=>[0]})
      @people = Security::Person.find(:all,:conditions=>{:deleted=>[0]})
      @conservationalstates = CulturalHeritage::ConservationalState.find(:all,:conditions=>{:deleted=>[0]})
      @integritystates = CulturalHeritage::IntegrityState.find(:all,:conditions=>{:deleted=>[0]})
      @shapes = CulturalHeritage::Shape.find(:all,:conditions=>{:deleted=>[0]})
      @techniques = CulturalHeritage::Technique.find(:all,:conditions=>{:deleted=>[0]})
      @topics = CulturalHeritage::Topic.find(:all,:conditions=>{:deleted=>[0]})
      respond_to do |format|
        format.html # new.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  # GET /cultural_heritage/cultural_heritages/1/edit
  def edit
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
    @title_view = 'Patrimonio Cultural Inmueble'
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
    @states = CulturalHeritage::State.find(:all,:conditions=>{:deleted=>[0]})
    @groups = CulturalHeritage::Group.find(:all,:conditions=>{:deleted=>[0]})
    @subgroups = CulturalHeritage::SubGroup.find(:all,:conditions=>{:deleted=>[0]})
    @typologies = []
    @culturalinstitutionstypes = CulturalHeritage::TypeCulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
    @inmuebles = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
    if ! @cultural_heritage_cultural_heritage.typeCulturalInstitution.blank?
      if @cultural_heritage_cultural_heritage.typeCulturalInstitution == 1
        @culturalinstitutions = CulturalHeritage::CulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
      end
      if @cultural_heritage_cultural_heritage.typeCulturalInstitution == 2
        @culturalinstitutions = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
      end
    else
      @culturalinstitutions = []
    end
    if ! @cultural_heritage_cultural_heritage.subGroup.blank?
      d = DateTime.new(1532,1,1)
      if @cultural_heritage_cultural_heritage.subGroup ==  1
      #Arqueologico
        @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and ((cultural_heritage_periods.enddate < ? and cultural_heritage_periods.dcFin = true) or (cultural_heritage_periods.dcFin = false))",0,d])
      else
      #Historico
        @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and (cultural_heritage_periods.startdate > ? and cultural_heritage_periods.dcInicio = true)",0,d])
      end
      @typologies = CulturalHeritage::Tipology.find(:all,:conditions=>["cultural_heritage_tipologies.deleted = ? and cultural_heritage_tipologies.group = ? and cultural_heritage_tipologies.subGroup = ?",0,2,@cultural_heritage_cultural_heritage.subGroup])
    else
      @periods = []
      @typologies = []
    end
    @cultures = @cultural_heritage_cultural_heritage.obj_period.list_obj_cultures   
    @styles = CulturalHeritage::Style.find(:all,:conditions=>{:deleted=>[0]})
    @people = Security::Person.find(:all,:conditions=>{:deleted=>[0]})
    @conservationalstates = CulturalHeritage::ConservationalState.find(:all,:conditions=>{:deleted=>[0]})
    @integritystates = CulturalHeritage::IntegrityState.find(:all,:conditions=>{:deleted=>[0]})
    @shapes = CulturalHeritage::Shape.find(:all,:conditions=>{:deleted=>[0]})
    @techniques = CulturalHeritage::Technique.find(:all,:conditions=>{:deleted=>[0]})
    @topics = CulturalHeritage::Topic.find(:all,:conditions=>{:deleted=>[0]})
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  # POST /cultural_heritage/cultural_heritages
  # POST /cultural_heritage/cultural_heritages.xml
  def create
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @title_view = 'Patrimonio Cultural Inmueble'
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.new(params[:cultural_heritage_cultural_heritage])
      @cultural_heritage_cultural_heritage.state = 5
      @inmuebles = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
      @groups = CulturalHeritage::Group.find(:all,:conditions=>{:deleted=>[0]})
      @subgroups = CulturalHeritage::SubGroup.find(:all,:conditions=>{:deleted=>[0]})
      @typologies = []
      @culturalinstitutionstypes = CulturalHeritage::TypeCulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
      if ! @cultural_heritage_cultural_heritage.typeCulturalInstitution.blank?
        if @cultural_heritage_cultural_heritage.typeCulturalInstitution == 1
          @culturalinstitutions = CulturalHeritage::CulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
        end
        if @cultural_heritage_cultural_heritage.typeCulturalInstitution == 2
          @culturalinstitutions = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
        end
      else
        @culturalinstitutions = []
      end
      if ! @cultural_heritage_cultural_heritage.subGroup.blank?
        d = DateTime.new(1532,1,1)
        if @cultural_heritage_cultural_heritage.subGroup ==  1
        #Arqueologico
          @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and ((cultural_heritage_periods.enddate < ? and cultural_heritage_periods.dcFin = true) or (cultural_heritage_periods.dcFin = false))",0,d])
        else
        #Historico
          @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and (cultural_heritage_periods.startdate > ? and cultural_heritage_periods.dcInicio = true)",0,d])
        end
        @typologies = CulturalHeritage::Tipology.find(:all,:conditions=>["cultural_heritage_tipologies.deleted = ? and cultural_heritage_tipologies.group = ? and cultural_heritage_tipologies.subGroup = ?",0,2,@cultural_heritage_cultural_heritage.subGroup])
      else
        @periods = []
        @typologies = []
      end
      @cultures = @cultural_heritage_cultural_heritage.obj_period.list_obj_cultures
      @styles = CulturalHeritage::Style.find(:all,:conditions=>{:deleted=>[0]})
      @people = Security::Person.find(:all,:conditions=>{:deleted=>[0]})
      @conservationalstates = CulturalHeritage::ConservationalState.find(:all,:conditions=>{:deleted=>[0]})
      @integritystates = CulturalHeritage::IntegrityState.find(:all,:conditions=>{:deleted=>[0]})
      @shapes = CulturalHeritage::Shape.find(:all,:conditions=>{:deleted=>[0]})
      @techniques = CulturalHeritage::Technique.find(:all,:conditions=>{:deleted=>[0]})
      @topics = CulturalHeritage::Topic.find(:all,:conditions=>{:deleted=>[0]})
      @cultural_heritage_cultural_heritage.group=2
      if !(@cultural_heritage_cultural_heritage.longitude.blank? or @cultural_heritage_cultural_heritage.latitude.blank?)
        @cultural_heritage_cultural_heritage.gmaps = true
      else
        @cultural_heritage_cultural_heritage.gmaps = false
        @cultural_heritage_cultural_heritage.longitude = nil
        @cultural_heritage_cultural_heritage.latitude = nil
      end
      respond_to do |format|
        if @cultural_heritage_cultural_heritage.save
          require "rubygems"
          require "twitter"
          require "bitly"
          Bitly.use_api_version_3
          service = Bitly.new('shintta','R_ee3152419b933c10bc5ae686768b0db5')
          #litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://www.pukara.ya.st/'))
          litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://200.16.7.111/'))
          Twitter.configure do |config|
            config.consumer_key = 'HbnrwjUSu6e60ar4HsIFyA'
            config.consumer_secret = 'ux0QzkfITjkpyDHQhW1QdMUYtdOKEUOSIZaSUUVgnbg'
            config.oauth_token = '604661480-WaD9NvyeYaYMzNPvdIC8aMPZiXw5kZujI1FsRYgk'
            config.oauth_token_secret = 'SovPXMbLrFzrnYJuw6z1CkZp7Rr1CcXEeGND4vXKvWE'
          end
          client = Twitter::Client.new
          if !litle_url.blank?
            client.update("#Pukara Se ha registrado un nuevo Patrimonio Cultural Inmueble "+@cultural_heritage_cultural_heritage.name+" "+ litle_url.short_url+"")
          else
            client.update("#Pukara Se ha registrado un nuevo Patrimonio Cultural Inmueble "+@cultural_heritage_cultural_heritage.name+" ")
          end
          format.html { redirect_to({:controller=>"/cultural_heritage/cultural_heritage_properties", :action=>"show", :id=>@cultural_heritage_cultural_heritage.id}, :notice => 'Se ha creado correctamente el patrimonio cultural inmueble.') }
          format.xml  { render :xml => @cultural_heritage_cultural_heritage, :status => :created, :location => @cultural_heritage_cultural_heritage }
        else
          format.html { render :action => "new"}
          format.xml  { render :xml => @cultural_heritage_cultural_heritage.errors, :status => :unprocessable_entity }
        end
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  ## mi otro approve...Juan
   def approve

  @cultural_heritage_cultural_heritage_pre_register = CulturalHeritage::CulturalHeritagePreRegister.find(params[:id])

@cultural_heritage_cultural_heritage_pre_register.state=1
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.new

         registro = params[:search_input]

 @cultural_heritage_cultural_heritage.nationalRegistrationCode=registro
   @cultural_heritage_cultural_heritage.name =@cultural_heritage_cultural_heritage_pre_register.name
      @cultural_heritage_cultural_heritage.description =@cultural_heritage_cultural_heritage_pre_register.description
      @cultural_heritage_cultural_heritage.foundInId =@cultural_heritage_cultural_heritage_pre_register.foundInId
      @cultural_heritage_cultural_heritage.height =@cultural_heritage_cultural_heritage_pre_register.height
      @cultural_heritage_cultural_heritage.long =@cultural_heritage_cultural_heritage_pre_register.long
      @cultural_heritage_cultural_heritage.width =@cultural_heritage_cultural_heritage_pre_register.width
      @cultural_heritage_cultural_heritage.weight =@cultural_heritage_cultural_heritage_pre_register.weight
      @cultural_heritage_cultural_heritage.state =@cultural_heritage_cultural_heritage_pre_register.state
      @cultural_heritage_cultural_heritage.group =@cultural_heritage_cultural_heritage_pre_register.group
      @cultural_heritage_cultural_heritage.subGroup =@cultural_heritage_cultural_heritage_pre_register.subGroup
      @cultural_heritage_cultural_heritage.tipology =@cultural_heritage_cultural_heritage_pre_register.tipology
      @cultural_heritage_cultural_heritage.typeCulturalInstitution =@cultural_heritage_cultural_heritage_pre_register.typeCulturalInstitution
      @cultural_heritage_cultural_heritage.culturalInstitution =@cultural_heritage_cultural_heritage_pre_register.culturalInstitution
      @cultural_heritage_cultural_heritage.period =@cultural_heritage_cultural_heritage_pre_register.period
      @cultural_heritage_cultural_heritage.culture =@cultural_heritage_cultural_heritage_pre_register.culture
      @cultural_heritage_cultural_heritage.style =@cultural_heritage_cultural_heritage_pre_register.style
      @cultural_heritage_cultural_heritage.owner =@cultural_heritage_cultural_heritage_pre_register.owner
       @cultural_heritage_cultural_heritage.author =@cultural_heritage_cultural_heritage_pre_register.author

     @cultural_heritage_cultural_heritage.conservationalState  =@cultural_heritage_cultural_heritage_pre_register.conservationalState

     @cultural_heritage_cultural_heritage.integrityState =@cultural_heritage_cultural_heritage_pre_register.integrityState

     @cultural_heritage_cultural_heritage.shape =@cultural_heritage_cultural_heritage_pre_register.shape
     @cultural_heritage_cultural_heritage.technique =@cultural_heritage_cultural_heritage_pre_register.technique

     @cultural_heritage_cultural_heritage.topic =@cultural_heritage_cultural_heritage_pre_register.topic

respond_to do |format|
      if @cultural_heritage_cultural_heritage.save
        require "rubygems"
        require "twitter"
        require "bitly"
        Bitly.use_api_version_3
        service = Bitly.new('shintta','R_ee3152419b933c10bc5ae686768b0db5')
        #litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://www.pukara.ya.st/'))
        litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://200.16.7.111/'))
        Twitter.configure do |config|
          config.consumer_key = 'HbnrwjUSu6e60ar4HsIFyA'
          config.consumer_secret = 'ux0QzkfITjkpyDHQhW1QdMUYtdOKEUOSIZaSUUVgnbg'
          config.oauth_token = '604661480-WaD9NvyeYaYMzNPvdIC8aMPZiXw5kZujI1FsRYgk'
          config.oauth_token_secret = 'SovPXMbLrFzrnYJuw6z1CkZp7Rr1CcXEeGND4vXKvWE'
        end
        client = Twitter::Client.new
        if !litle_url.blank?
          client.update("#Pukara Se ha registrado un nuevo Patrimonio Cultural Inmueble "+@cultural_heritage_cultural_heritage.name+" "+ litle_url.short_url+"")
        else
          client.update("#Pukara Se ha registrado un nuevo Patrimonio Cultural Inmueble "+@cultural_heritage_cultural_heritage.name+" ")
        end
        #client.update("#Pukara Se ha registrado un nuevo Patrimonio Cultural ("+@cultural_heritage_cultural_heritage.name+") "+ @cultural_heritage_cultural_heritage.show_url(root_url)+"")
        format.html { redirect_to(@cultural_heritage_cultural_heritage, :notice => 'Cultural heritage was successfully created.') }
        format.xml  { render :xml => @cultural_heritage_cultural_heritage, :status => :created, :location => @cultural_heritage_cultural_heritage }
      else
        format.html { render :action => "new"}
        format.xml  { render :xml => @cultural_heritage_cultural_heritage.errors, :status => :unprocessable_entity }
      end
    end

#      cultural_heritage_cultural_heritage.save

end


  # PUT /cultural_heritage/cultural_heritages/1
  # PUT /cultural_heritage/cultural_heritages/1.xml
  def update
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @title_view = 'Patrimonio Cultural Inmueble'
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage.attributes = params[:cultural_heritage_cultural_heritage]
      @inmuebles = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
      @groups = CulturalHeritage::Group.find(:all,:conditions=>{:deleted=>[0]})
      @subgroups = CulturalHeritage::SubGroup.find(:all,:conditions=>{:deleted=>[0]})
      @typologies = []
      @culturalinstitutionstypes = CulturalHeritage::TypeCulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
      if ! @cultural_heritage_cultural_heritage.typeCulturalInstitution.blank?
        if @cultural_heritage_cultural_heritage.typeCulturalInstitution == 1
          @culturalinstitutions = CulturalHeritage::CulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
        end
        if @cultural_heritage_cultural_heritage.typeCulturalInstitution == 2
          @culturalinstitutions = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
        end
      else
        @culturalinstitutions = []
      end
      if ! @cultural_heritage_cultural_heritage.subGroup.blank?
        d = DateTime.new(1532,1,1)
        if @cultural_heritage_cultural_heritage.subGroup ==  1
        #Arqueologico
          @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and ((cultural_heritage_periods.enddate < ? and cultural_heritage_periods.dcFin = true) or (cultural_heritage_periods.dcFin = false))",0,d])
        else
        #Historico
          @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and (cultural_heritage_periods.startdate > ? and cultural_heritage_periods.dcInicio = true)",0,d])
        end
        @typologies = CulturalHeritage::Tipology.find(:all,:conditions=>["cultural_heritage_tipologies.deleted = ? and cultural_heritage_tipologies.group = ? and cultural_heritage_tipologies.subGroup = ?",0,2,@cultural_heritage_cultural_heritage.subGroup])
      else
        @periods = []
        @typologies = []
      end
      @cultures = @cultural_heritage_cultural_heritage.obj_period.list_obj_cultures
      @styles = CulturalHeritage::Style.find(:all,:conditions=>{:deleted=>[0]})
      @people = Security::Person.find(:all,:conditions=>{:deleted=>[0]})
      @conservationalstates = CulturalHeritage::ConservationalState.find(:all,:conditions=>{:deleted=>[0]})
      @integritystates = CulturalHeritage::IntegrityState.find(:all,:conditions=>{:deleted=>[0]})
      @shapes = CulturalHeritage::Shape.find(:all,:conditions=>{:deleted=>[0]})
      @techniques = CulturalHeritage::Technique.find(:all,:conditions=>{:deleted=>[0]})
      @topics = CulturalHeritage::Topic.find(:all,:conditions=>{:deleted=>[0]})
      if !(@cultural_heritage_cultural_heritage.longitude.blank? or @cultural_heritage_cultural_heritage.latitude.blank?)
        @cultural_heritage_cultural_heritage.gmaps = true
      else
        @cultural_heritage_cultural_heritage.gmaps = false
        @cultural_heritage_cultural_heritage.longitude = nil
        @cultural_heritage_cultural_heritage.latitude = nil
      end
      respond_to do |format|        
        if @cultural_heritage_cultural_heritage.save  
          format.html {redirect_to({:controller=>"/cultural_heritage/cultural_heritage_properties", :action=>"show", :id=>@cultural_heritage_cultural_heritage.id}, :notice => 'Se ha actualizado correctamente el patrimonio cultural inmueble.')}
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @cultural_heritage_cultural_heritage.errors, :status => :unprocessable_entity }
        end
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def change_cultural_institutions
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.new
    if params[:id].to_i ==  1
      @culturalinstitutions = CulturalHeritage::CulturalInstitution.find(:all,:conditions=>{:deleted=>[0]})
    else
      @culturalinstitutions = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:deleted=>[0],:group=>2})
    end
    render :partial=>"insti_cultu", :layout=>false
  end

  def change_periods
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.new
    #1534 como punto de inflexion
    d = DateTime.new(1532,1,1)
    if params[:id].to_i ==  1
      #Arqueologico
        @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and ((cultural_heritage_periods.enddate < ? and cultural_heritage_periods.dcFin = true) or (cultural_heritage_periods.dcFin = false))",0,d])
      else
      #Historico
        @periods = CulturalHeritage::Period.find(:all,:conditions=>["cultural_heritage_periods.deleted = ? and (cultural_heritage_periods.startdate > ? and cultural_heritage_periods.dcInicio = true)",0,d])
      end
    render :partial=>"period", :layout=>false
  end
  
  def change_cultures
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.new
    #1534 como punto de inflexion
    @obj_period = CulturalHeritage::Period.find(params[:id].to_i)
    @cultures = @obj_period.list_obj_cultures
    render :partial=>"culture", :layout=>false
  end


  def change_tipologies
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.new    
      if ! params[:subgroup].blank?
        @typologies = CulturalHeritage::Tipology.find(:all,:conditions=>["cultural_heritage_tipologies.deleted = ? and cultural_heritage_tipologies.group = ? and cultural_heritage_tipologies.subGroup = ?",0,2,params[:subgroup].to_i])
      else
        @typologies = CulturalHeritage::Tipology.find(:all,:conditions=>["cultural_heritage_tipologies.deleted = ? and cultural_heritage_tipologies.group = ? ",0,2])
      end   
    render :partial=>"tipology", :layout=>false
  end

  # DELETE /cultural_heritage/cultural_heritages/1
  # DELETE /cultural_heritage/cultural_heritages/1.xml
  def delete
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      #@cultural_heritage_cultural_heritage.destroy
      @cultural_heritage_cultural_heritage.deleted = 1
      @cultural_heritage_cultural_heritage.save
      respond_to do |format|
        format.html { redirect_to(:controller=>"/cultural_heritage/cultural_heritage_properties",:action => 'index') }
        format.xml  { head :ok }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def update_table
#    @search_name = params[:search_name]
#    if ! @search_name.blank?
#      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.group = ? and (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ?)",2,'%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%'])
#      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:joins=>[:obj_tipology,:obj_culture,:obj_period],:conditions=>["cultural_heritage_cultural_heritages.group = ? and (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ? or cultural_heritage_cultural_heritages.nationalRegistrationCode LIKE ? or cultural_heritage_tipologies.name LIKE ? or cultural_heritage_cultures.name LIKE ? or cultural_heritage_periods.name LIKE ?)",2,'%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%'])
#    else
#      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:group=>[2],:deleted=>[0]})
#    end
#    render :partial => "table"
      @search_input = params[:search_name].to_s
      @search_field = params[:field_name].to_s

      @cultural_heritage_cultural_heritages = nil

        case @search_field
          when "Todos" then  @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:joins=>[
                              'LEFT OUTER JOIN `cultural_heritage_periods` ON `cultural_heritage_periods`.`id` = `cultural_heritage_cultural_heritages`.`period`',
                              'LEFT OUTER JOIN `cultural_heritage_states` ON `cultural_heritage_states`.`id` = `cultural_heritage_cultural_heritages`.`state`',
                              'LEFT OUTER JOIN `cultural_heritage_cultures` ON `cultural_heritage_cultures`.`id` = `cultural_heritage_cultural_heritages`.`culture`'
                              ],:conditions=>["cultural_heritage_cultural_heritages.group = ? and (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_periods.name LIKE ? or cultural_heritage_states.name LIKE ? or cultural_heritage_cultural_heritages.nationalRegistrationCode LIKE ? or cultural_heritage_cultures.name LIKE ? )",2,'%'+@search_input+'%','%'+@search_input+'%','%'+@search_input+'%','%'+@search_input+'%','%'+@search_input+'%'])
          when "Nombre" then @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.group = ? and cultural_heritage_cultural_heritages.name LIKE ? ",2,'%'+@search_input+'%'])
          when "Periodo" then @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all, :joins=>'LEFT OUTER JOIN `cultural_heritage_periods` ON `cultural_heritage_periods`.`id` = `cultural_heritage_cultural_heritages`.`period`', :conditions=>["cultural_heritage_cultural_heritages.group = ? and cultural_heritage_periods.name LIKE ?",2,"%"+@search_input+"%"])
          when "Estado" then @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all, :joins=>'LEFT OUTER JOIN `cultural_heritage_states` ON `cultural_heritage_states`.`id` = `cultural_heritage_cultural_heritages`.`state`', :conditions=>["cultural_heritage_cultural_heritages.group = ? and cultural_heritage_states.name LIKE ?",2,"%"+@search_input+"%"])
          when "Cultura" then @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all, 'LEFT OUTER JOIN `cultural_heritage_cultures` ON `cultural_heritage_cultures`.`id` = `cultural_heritage_cultural_heritages`.`culture`', :conditions=>["cultural_heritage_cultural_heritages.group = ? and cultural_heritage_cultures.name LIKE ?",2,"%"+@search_input+"%"])
        end



  end

  def gallery
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @title_view = 'Patrimonio Cultural Inmueble'
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_avatars = @cultural_heritage_cultural_heritage.list_avatars
      respond_to do |format|
        format.html {render :layout => "blank"}# index.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage_avatars }
        format.json  { render :json => @cultural_heritage_cultural_heritage_avatars }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def new_photo
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @title_view = 'Patrimonio Cultural Inmueble'
      @cultural_heritage_cultural_heritage_avatar = CulturalHeritage::CulturalHeritageAvatar.new()
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_avatar.cultural_heritage = params[:id]
      respond_to do |format|
        format.html {render :layout => "blank"}# new.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage_avatar }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def create_photo
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @title_view = 'Patrimonio Cultural Inmueble'
      @cultural_heritage_cultural_heritage_avatar = CulturalHeritage::CulturalHeritageAvatar.new(params[:cultural_heritage_cultural_heritage_avatar])
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_avatar.cultural_heritage = params[:id]
      respond_to do |format|
        if @cultural_heritage_cultural_heritage_avatar.save
          require "rubygems"
          require "twitter"
          require "bitly"
          Bitly.use_api_version_3
          service = Bitly.new('shintta','R_ee3152419b933c10bc5ae686768b0db5')
          #litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://www.pukara.ya.st/'))
          litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://200.16.7.111/'))
          Twitter.configure do |config|
            config.consumer_key = 'HbnrwjUSu6e60ar4HsIFyA'
            config.consumer_secret = 'ux0QzkfITjkpyDHQhW1QdMUYtdOKEUOSIZaSUUVgnbg'
            config.oauth_token = '604661480-WaD9NvyeYaYMzNPvdIC8aMPZiXw5kZujI1FsRYgk'
            config.oauth_token_secret = 'SovPXMbLrFzrnYJuw6z1CkZp7Rr1CcXEeGND4vXKvWE'
          end
          client = Twitter::Client.new
          if !litle_url.blank?
            client.update("#Pukara Se ha registrado una nueva foto ("+@cultural_heritage_cultural_heritage_avatar.title+") en "+@cultural_heritage_cultural_heritage.name+" "+ litle_url.short_url+"")
          else
            client.update("#Pukara Se ha registrado una nueva foto ("+@cultural_heritage_cultural_heritage_avatar.title+") en "+@cultural_heritage_cultural_heritage.name+" ")
          end
          #client.update("#Pukara Se ha registrado una nueva foto ("+@cultural_heritage_cultural_heritage_avatar.title+") en "+@cultural_heritage_cultural_heritage.name+" "+ @cultural_heritage_cultural_heritage.show_url(root_url)+"")
          format.html { redirect_to({:controller=>"/cultural_heritage/cultural_heritage_properties",:action => 'gallery',:id => @cultural_heritage_cultural_heritage_avatar.cultural_heritage}, :notice => 'Se ha agregado correctamente una nueva imagen.',:layout => "blank") }
          format.xml  { render :xml => @cultural_heritage_cultural_heritage_avatar, :status => :created, :location => @cultural_heritage_cultural_heritage_avatar }
        else
          format.html { render :action => "new_photo",:controller=>"/cultural_heritage/cultural_heritage_properties",:layout => "blank"}
          format.xml  { render :xml => @cultural_heritage_cultural_heritage_avatar.errors, :status => :unprocessable_entity }
        end
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def delete_photo
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage_avatar = CulturalHeritage::CulturalHeritageAvatar.find(params[:id])
      @cultural_heritage_cultural_heritage_avatar.deleted = 1
      @cultural_heritage_cultural_heritage_avatar.save
      respond_to do |format|
        format.html { redirect_to(:controller=>"/cultural_heritage/cultural_heritage_properties",:action => 'gallery',:id =>@cultural_heritage_cultural_heritage_avatar.cultural_heritage) }
        format.xml  { head :ok }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def assing
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @title_view = 'Patrimonio Cultural Inmueble'
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_institutions = CulturalHeritage::CulturalInstitution.all
      @states = CulturalHeritage::State.all
      @groups = CulturalHeritage::Group.all
      @subgroups = CulturalHeritage::SubGroup.all
      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["(cultural_heritage_cultural_heritages.foundInId IS NULL or cultural_heritage_cultural_heritages.foundInId = ?) and cultural_heritage_cultural_heritages.id != ?",@cultural_heritage_cultural_heritage.id,@cultural_heritage_cultural_heritage.id])
      @assignments_list = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.foundInId = ?",@cultural_heritage_cultural_heritage.id])
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def update_assing_table
    @search_name = params[:search_name]
    @cultural_institution = params[:cultural_institution][:id]
    @start_date = params[:calendar][:start_date]
    @end_date = params[:calendar][:end_date]
    @search_state = params[:search_state]
    @search_group = params[:search_group]
    @search_subgroup = params[:search_subgroup]
    @cultural_heritage_id = params[:cultural_heritage_id]
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(@cultural_heritage_id.to_i)
    my_heritage_conditions  = String.new
    my_heritage_values      = Array.new
    my_heritage_conditions << "(cultural_heritage_cultural_heritages.foundInId IS NULL) "
    my_heritage_conditions << "AND cultural_heritage_cultural_heritages.id != ? "
    my_heritage_values.push(@cultural_heritage_id)
    if @cultural_heritage_cultural_heritage.father_maximum_id != -1
      my_heritage_conditions << "AND cultural_heritage_cultural_heritages.id != ? "
      my_heritage_values.push(@cultural_heritage_cultural_heritage.father_maximum_id)
    end    
    if (! @search_name.blank?)
      my_heritage_conditions << "AND (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ? or cultural_heritage_cultural_heritages.nationalRegistrationCode LIKE ?) "
      my_heritage_values.push('%'+@search_name+'%')
      my_heritage_values.push('%'+@search_name+'%')
      my_heritage_values.push('%'+@search_name+'%')
      my_heritage_values.push('%'+@search_name+'%')
    end

    if (!@cultural_institution.blank?)
      my_heritage_conditions << "AND (cultural_heritage_cultural_heritages.typeCulturalInstitution = 1 and cultural_heritage_cultural_heritages.culturalInstitution = ?) "
      my_heritage_values.push(@cultural_institution)
    end

    if (! @start_date.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.created_at >= ?) "
        my_heritage_values.push(@start_date.to_date)
    end

    if (!@end_date.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.created_at <= ?) "
        my_heritage_values.push(@end_date.to_date)
    end

    if (!@search_state.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.state = ?) "
        my_heritage_values.push(@search_state)
    end

    if (!@search_group.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.group = ?) "
        my_heritage_values.push(@search_group)
    end

    if (!@search_subgroup.blank?)
        my_heritage_conditions << " AND (cultural_heritage_cultural_heritages.subGroup = ?) "
        my_heritage_values.push(@search_subgroup)
    end
    my_heritage_values.insert(0, my_heritage_conditions)
    @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=> my_heritage_values)    
    render :partial => "assing_table"
  end

  def save_assignments
    @title_view = 'Patrimonio Cultural Inmueble'
    if params[:cultural_heritage_selected].blank?
      selecteds_ids = []
    else
      selecteds_ids=params[:cultural_heritage_selected]
    end
    
    cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:cultural_heritage_id])
    selected_cultural_heritages = []
    
    selecteds_ids.each do |selected_id|
      selected_cultural_heritages << CulturalHeritage::CulturalHeritage.find(selected_id)
    end
    
    assignments_list = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>["cultural_heritage_cultural_heritages.foundInId = ?",cultural_heritage.id])

    assignments_to_save_list = []
    selected_cultural_heritages.each do |selected_cultural_heritage|
      selected_cultural_heritage.foundInId = cultural_heritage.id
      assignments_to_save_list << selected_cultural_heritage
    end

    assignments_list.each do |old_assing|
      is_in = false
      selected_cultural_heritages.each do |selected_cultural_heritage|
        if (old_assing.id == selected_cultural_heritage.id)
          is_in = true
          break
        end
      end
      if (! is_in)
        old_assing.foundInId = nil
        assignments_to_save_list << old_assing
      end
    end
    no_problem = true
    assignments_to_save_list.each do |assignment_to_save|
      s_cultural_heritage = CulturalHeritage::CulturalHeritage.find(assignment_to_save.id)
      if (s_cultural_heritage.foundInId.blank? or s_cultural_heritage.foundInId == cultural_heritage.id )
        assignment_to_save.save
      else
        no_problem = false
      end
    end
    if (no_problem)
      respond_to do |format|
        format.html { redirect_to(:controller=>"/cultural_heritage/cultural_heritage_properties",:action => 'show',:id =>cultural_heritage.id, :notice => 'Asignacion exitosa.') }
        flash[:notice] = 'Asignacion exitosa.'
        format.xml  { head :ok }
      end
    else
      respond_to do |format|
        format.html { redirect_to(:controller=>"/cultural_heritage/cultural_heritage_properties",:action => 'assing',:id =>cultural_heritage.id, :notice => 'Se han generado problemas asignando algunos elementos.')}
          flash[:notice] = 'Se han generado problemas asignando algunos elementos.'
        #format.xml  { render :xml => @cultural_heritage_cultural_heritage.errors, :status => :unprocessable_entity }
      end
    end    
  end

 def researches
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_researches = @cultural_heritage_cultural_heritage.list_researches
      respond_to do |format|
        format.html {render :layout => "blank"}# index.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage_researches }
        format.json { render :json => @cultural_heritage_cultural_heritage_researches }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def new_research
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
    @cultural_heritage_cultural_heritage_research = CulturalHeritage::CulturalHeritageFile.new()
    @cultural_heritage_cultural_heritage_research.cultural_heritage = params[:id]
    respond_to do |format|
      format.html {render :layout => "blank"}# index.html.erb
      format.xml  { render :xml => @cultural_heritage_cultural_heritage_research }
      format.json { render :json => @cultural_heritage_cultural_heritage_research }
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def create_research
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
    @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
    @cultural_heritage_cultural_heritage_research = CulturalHeritage::CulturalHeritageFile.new(params[:cultural_heritage_cultural_heritage_file])
    @cultural_heritage_cultural_heritage_research.cultural_heritage = params[:id]
    if (user_signed_in?)
      @cultural_heritage_cultural_heritage_research.user = current_user.id
    end
    respond_to do |format|
      if @cultural_heritage_cultural_heritage_research.save
        require "rubygems"
        require "twitter"
        require "bitly"
        Bitly.use_api_version_3
        service = Bitly.new('shintta','R_ee3152419b933c10bc5ae686768b0db5')
        #litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://www.pukara.ya.st/'))
        litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://200.16.7.111/'))
        Twitter.configure do |config|
          config.consumer_key = 'HbnrwjUSu6e60ar4HsIFyA'
          config.consumer_secret = 'ux0QzkfITjkpyDHQhW1QdMUYtdOKEUOSIZaSUUVgnbg'
          config.oauth_token = '604661480-WaD9NvyeYaYMzNPvdIC8aMPZiXw5kZujI1FsRYgk'
          config.oauth_token_secret = 'SovPXMbLrFzrnYJuw6z1CkZp7Rr1CcXEeGND4vXKvWE'
        end        
        client = Twitter::Client.new       
        #litle_url = @cultural_heritage_cultural_heritage.show_url(root_url)
        if !litle_url.blank?
          client.update("#Pukara Se ha registrado una nueva investigacion ("+@cultural_heritage_cultural_heritage_research.title+") en "+@cultural_heritage_cultural_heritage.name+" "+ litle_url.short_url+"")
        else
          client.update("#Pukara Se ha registrado una nueva investigacion ("+@cultural_heritage_cultural_heritage_research.title+") en "+@cultural_heritage_cultural_heritage.name+" ")
        end        
        @cultural_heritage_cultural_heritage.list_researchers.each do |researcher|
           ResearchMailer.registered_research(@cultural_heritage_cultural_heritage_research, researcher).deliver
        end        
        format.html { redirect_to({:action => 'researches',:id => @cultural_heritage_cultural_heritage_research.cultural_heritage}, :notice => 'Se ha agregado correctamente una nueva Investigacion.') }
        #format.xml  { render :xml => @cultural_heritage_cultural_heritage_research, :status => :created, :location => @cultural_heritage_cultural_heritage_research }
      else
        format.html { render :action => "new_research",:layout => "blank"}
        #format.xml  { render :xml => @cultural_heritage_cultural_heritage_research.errors, :status => :unprocessable_entity }
      end
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def delete_research
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
    @cultural_heritage_cultural_heritage_research = CulturalHeritage::CulturalHeritageFile.find(params[:id])
    @cultural_heritage_cultural_heritage_research.deleted = 1
    @cultural_heritage_cultural_heritage_research.save
    respond_to do |format|
      format.html { redirect_to(:action => 'researches',:id =>@cultural_heritage_cultural_heritage_research.cultural_heritage,:layout => "blank") }
      format.xml  { head :ok }
    end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def show_file
    @cultural_heritage_cultural_heritage_research = CulturalHeritage::CulturalHeritageFile.find(params[:id])
    txt = "public/system/researches/"
    send_file(txt + params[:id] + "/original/"+ @cultural_heritage_cultural_heritage_research.research_file_name )
  end

  def show_research
    @cultural_heritage_cultural_heritage_research = CulturalHeritage::CulturalHeritageFile.find(params[:id])
    @cultural_heritage_cultural_heritage = @cultural_heritage_cultural_heritage_research.obj_cultural_heritage
    respond_to do |format|
      format.html  {render :layout => "blank"}
      format.xml  { render :xml => @cultural_heritage_cultural_heritage_research }
      format.json  { render :json => @cultural_heritage_cultural_heritage_research }
    end      
  end

  def videos
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_videos = @cultural_heritage_cultural_heritage.list_videos
      respond_to do |format|
        format.html {render :layout => "blank"}# index.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage_videos }
        format.json { render :json => @cultural_heritage_cultural_heritage_videos }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def new_video
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_video = CulturalHeritage::CulturalHeritageYoutube.new()
      @cultural_heritage_cultural_heritage_video.cultural_heritage = params[:id]
      respond_to do |format|
        format.html {render :layout => "blank"}# index.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage_video }
        format.json { render :json => @cultural_heritage_cultural_heritage_video }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def create_video
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_video = CulturalHeritage::CulturalHeritageYoutube.new(params[:cultural_heritage_cultural_heritage_youtube])
      @cultural_heritage_cultural_heritage_video.cultural_heritage = params[:id]
      if (user_signed_in?)
        @cultural_heritage_cultural_heritage_video.user = current_user.id
      end
      respond_to do |format|
        if @cultural_heritage_cultural_heritage_video.save
          require "rubygems"
          require "twitter"
          require "bitly"
          Bitly.use_api_version_3
          service = Bitly.new('shintta','R_ee3152419b933c10bc5ae686768b0db5')
          #litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://www.pukara.ya.st/'))
          litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://200.16.7.111/'))
          Twitter.configure do |config|
            config.consumer_key = 'HbnrwjUSu6e60ar4HsIFyA'
            config.consumer_secret = 'ux0QzkfITjkpyDHQhW1QdMUYtdOKEUOSIZaSUUVgnbg'
            config.oauth_token = '604661480-WaD9NvyeYaYMzNPvdIC8aMPZiXw5kZujI1FsRYgk'
            config.oauth_token_secret = 'SovPXMbLrFzrnYJuw6z1CkZp7Rr1CcXEeGND4vXKvWE'
          end
          client = Twitter::Client.new
          if !litle_url.blank?
            client.update("#Pukara Se ha registrado un nuevo video ("+@cultural_heritage_cultural_heritage_video.title+") en "+@cultural_heritage_cultural_heritage.name+" "+ litle_url.short_url+"")
          else
            client.update("#Pukara Se ha registrado un nuevo video ("+@cultural_heritage_cultural_heritage_video.title+") en "+@cultural_heritage_cultural_heritage.name+" ")
          end
          #client.update("#Pukara Se ha registrado un nuevo video ("+@cultural_heritage_cultural_heritage_video.title+") en "+@cultural_heritage_cultural_heritage.name+" "+ @cultural_heritage_cultural_heritage.show_url(root_url)+"")
          format.html { redirect_to({:action => 'videos',:id => @cultural_heritage_cultural_heritage_video.cultural_heritage}, :notice => 'Se ha agregado correctamente un nuevo video.') }
          #format.xml  { render :xml => @cultural_heritage_cultural_heritage_research, :status => :created, :location => @cultural_heritage_cultural_heritage_research }
        else
          format.html { render :action => "new_video",:layout => "blank"}
          #format.xml  { render :xml => @cultural_heritage_cultural_heritage_research.errors, :status => :unprocessable_entity }
        end
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def delete_video
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage_video = CulturalHeritage::CulturalHeritageYoutube.find(params[:id])
      @cultural_heritage_cultural_heritage_video.deleted = 1
      @cultural_heritage_cultural_heritage_video.save
      respond_to do |format|
        format.html { redirect_to(:action => 'videos',:id =>@cultural_heritage_cultural_heritage_video.cultural_heritage,:layout => "blank") }
        format.xml  { head :ok }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def gmaps_search
    @title_view = 'Patrimonio Cultural Inmueble'
    @search_name = params[:search_name]
    if ! @search_name.blank?      
      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:joins=>[
          :obj_tipology,
          'LEFT OUTER JOIN `cultural_heritage_periods` ON `cultural_heritage_periods`.`id` = `cultural_heritage_cultural_heritages`.`period`',                              
          'LEFT OUTER JOIN `cultural_heritage_cultures` ON `cultural_heritage_cultures`.`id` = `cultural_heritage_cultural_heritages`.`culture`'
        ],:conditions=>["cultural_heritage_cultural_heritages.group = ? and (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ? or cultural_heritage_cultural_heritages.nationalRegistrationCode LIKE ? or cultural_heritage_tipologies.name LIKE ? or cultural_heritage_cultures.name LIKE ? or cultural_heritage_periods.name LIKE ?)",2,'%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%'])
    else      
      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:group=>[2],:deleted=>[0]})
    end
    @json = @cultural_heritage_cultural_heritages.to_gmaps4rails do |cultural_heritage, marker|      
      marker.infowindow  cultural_heritage.define_info_window_for_marker_for_maps(root_url)
      marker.title   cultural_heritage.name
      marker.sidebar cultural_heritage.name_code
    end    
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @cultural_heritage_cultural_heritages }
      format.json  { render :json => @cultural_heritage_cultural_heritages }
    end
  end

#  def update_gmap
#    @search_name = params[:search_name]
#    if ! @search_name.blank?
#      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:joins=>[:obj_tipology,:obj_culture,:obj_period],:conditions=>["cultural_heritage_cultural_heritages.group = ? and (cultural_heritage_cultural_heritages.name LIKE ? or cultural_heritage_cultural_heritages.description LIKE ? or cultural_heritage_cultural_heritages.materials LIKE ? or cultural_heritage_cultural_heritages.nationalRegistrationCode LIKE ? or cultural_heritage_tipologies.name LIKE ? or cultural_heritage_cultures.name LIKE ? or cultural_heritage_periods.name LIKE ?)",1,'%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%','%'+@search_name+'%'])
#    else
#      @cultural_heritage_cultural_heritages = CulturalHeritage::CulturalHeritage.find(:all,:conditions=>{:group=>[1],:deleted=>[0]})
#    end
#    @json = @cultural_heritage_cultural_heritages.to_gmaps4rails do |cultural_heritage, marker|
#      marker.infowindow  cultural_heritage.define_info_window_for_marker_for_maps(root_url)
#      marker.title   cultural_heritage.name
#      marker.sidebar "Ubicacion"
#    end
#    render :partial => "gmap"
#  end

  def models
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_models = @cultural_heritage_cultural_heritage.list_models
      respond_to do |format|
        format.html {render :layout => "blank"}# index.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage_models }
        format.json { render :json => @cultural_heritage_cultural_heritage_models }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def new_model
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_model = CulturalHeritage::Model3D.new()
      @cultural_heritage_cultural_heritage_model.cultural_heritage = params[:id]
      respond_to do |format|
        format.html {render :layout => "blank"}# index.html.erb
        format.xml  { render :xml => @cultural_heritage_cultural_heritage_model }
        format.json { render :json => @cultural_heritage_cultural_heritage_model }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def create_model
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage = CulturalHeritage::CulturalHeritage.find(params[:id])
      @cultural_heritage_cultural_heritage_model = CulturalHeritage::Model3D.new(params[:cultural_heritage_model3_d])
      @cultural_heritage_cultural_heritage_model.cultural_heritage = params[:id]
      if (user_signed_in?)
        @cultural_heritage_cultural_heritage_model.user = current_user.id
      end
      respond_to do |format|
        if @cultural_heritage_cultural_heritage_model.save
          require "rubygems"
          require "twitter"
          require "bitly"
          Bitly.use_api_version_3
          service = Bitly.new('shintta','R_ee3152419b933c10bc5ae686768b0db5')
          #litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://www.pukara.ya.st/'))
          litle_url = service.shorten(@cultural_heritage_cultural_heritage.show_url('http://200.16.7.111/'))
          Twitter.configure do |config|
            config.consumer_key = 'HbnrwjUSu6e60ar4HsIFyA'
            config.consumer_secret = 'ux0QzkfITjkpyDHQhW1QdMUYtdOKEUOSIZaSUUVgnbg'
            config.oauth_token = '604661480-WaD9NvyeYaYMzNPvdIC8aMPZiXw5kZujI1FsRYgk'
            config.oauth_token_secret = 'SovPXMbLrFzrnYJuw6z1CkZp7Rr1CcXEeGND4vXKvWE'
          end
          client = Twitter::Client.new
          if !litle_url.blank?
            client.update("#Pukara Se ha registrado un nuevo modelo 3D ("+@cultural_heritage_cultural_heritage_model.title+") en "+@cultural_heritage_cultural_heritage.name+" "+ litle_url.short_url+"")
          else
            client.update("#Pukara Se ha registrado un nuevo modelo 3D ("+@cultural_heritage_cultural_heritage_model.title+") en "+@cultural_heritage_cultural_heritage.name+" ")
          end
          #client.update("#Pukara Se ha registrado un nuevo video ("+@cultural_heritage_cultural_heritage_video.title+") en "+@cultural_heritage_cultural_heritage.name+" "+ @cultural_heritage_cultural_heritage.show_url(root_url)+"")
          format.html { redirect_to({:action => 'models',:id => @cultural_heritage_cultural_heritage_model.cultural_heritage}, :notice => 'Se ha agregado correctamente un nuevo modelo.') }
          #format.xml  { render :xml => @cultural_heritage_cultural_heritage_research, :status => :created, :location => @cultural_heritage_cultural_heritage_research }
        else
          format.html { render :action => "new_model",:layout => "blank"}
          #format.xml  { render :xml => @cultural_heritage_cultural_heritage_research.errors, :status => :unprocessable_entity }
        end
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def delete_model
    if (user_signed_in? && ([1,2,4].include?(current_user.role)))
      @cultural_heritage_cultural_heritage_model = CulturalHeritage::Model3D.find(params[:id])
      @cultural_heritage_cultural_heritage_model.deleted = 1
      @cultural_heritage_cultural_heritage_model.save
      respond_to do |format|
        format.html { redirect_to(:action => 'models',:layout => "blank",:id => @cultural_heritage_cultural_heritage_model.cultural_heritage) }
        format.xml  { head :ok }
      end
    else
      respond_to do |format|
        format.html { redirect_to(new_user_session_path) }
      end
    end
  end

  def follow
    if (user_signed_in?)
      validador = CulturalHeritage::Researcher.find(:all,:conditions=>["cultural_heritage_researchers.cultural_heritage = ? and cultural_heritage_researchers.user = ?",params[:id].to_i,current_user.id])
      @cultural_heritage_researcher = CulturalHeritage::Researcher.new
      @cultural_heritage_researcher.cultural_heritage = params[:id].to_i
      @cultural_heritage_researcher.user = current_user.id
      respond_to do |format|
        if validador.blank?
          if @cultural_heritage_researcher.save
            format.html { redirect_to({:controller=>"cultural_heritage/cultural_heritage_properties",:action => 'show',:id => params[:id].to_i}, :notice => 'Se asocio correctamente.') }
            format.xml  { head :ok }
          else
            format.html { redirect_to({:controller=>"cultural_heritage/cultural_heritage_properties",:action => 'show',:id => params[:id].to_i}, :notice => 'No se pudo asociar correctamente.') }
            format.xml  { render :xml => @cultural_heritage_researcher.errors, :status => :unprocessable_entity }
          end
        else
            format.html { redirect_to({:controller=>"cultural_heritage/cultural_heritage_properties",:action => 'show',:id => params[:id].to_i}, :notice => 'Ya se encuentra asociado.') }
            format.xml  { render :xml => @cultural_heritage_researcher.errors, :status => :unprocessable_entity }
        end
      end
    end
  end
end
